/*
 * @Descripttion:
 * @Author: YuZhenJing
 * @Date: 2020-01-01 12:52:58
 * @LastEditors: YuZhenJing
 * @LastEditTime: 2020-05-18 10:04:56
 */
import vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import Layout from '@/views/enter/Home.vue'
vue.use(Router)

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/login',
    component: () => import('@/views/enter/Login.vue')
  },
  {
    path: '/404',
    component: () => import('@/views/error/404')
  },
  {
    path: '/403',
    component: () => import('@/views/error/403')
  },
  {
    path: '/',
    component: Layout,
    redirect: 'dashboard',
    children: [
      {
        path: '/dashboard',
        name: '首页',
        component: () => import('@/views/dashboard/Index')
      },
      {
        path: '/test',
        name: '路由跳转测试',
        component: () => import('@/views/dashboard/TestRouter')
      },
      {
        path: '/body*',
        name: '主体子项目「包含总控相关功能」'
      }
    ]
  },
  { path: '*', redirect: '/404' }
]

const router = new Router({
  mode: 'history',
  routes: routes
})

const whiteList = ['/login', '/404', '/403'] // 设置白名单，避免死循环

router.beforeEach(async (to, from, next) => {
  const _this = new vue()
  if (whiteList.indexOf(to.path) !== -1) {
    if (to.path == '/login' && _this.$auth.token.get() != 'null') {
      _this.$auth.clearCache.all()
    }
    next()
  } else {
    const userObj = _this.$auth.userInfo.get()
    if (userObj && userObj.userId) {
      await _this.$coreHtml
        .get('login/router')
        .then(() => {
          store.commit('login/SET_USERINFO', _this.$auth.userInfo.get())
          store.commit('login/SET_MENUINFO', _this.$auth.menuInfo.get())
          next()
        })
        .catch(err => {
          if (err.response && err.response.status == '403') {
            next({ path: '/login' })
          } else {
            console.log(err)
          }
        })
    } else {
      next({ path: '/login' })
    }
  }
})

export default router
